import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _colors = [
    Colors.blue[100],
    Colors.blue[300],
    Colors.blue[500],
    Colors.blue[700],
    Colors.blue[900],
  ];
  late int _slot;

  final _globalKey = GlobalKey();
  late double _offset;

  _shuffle() {
    setState(() {
      _colors.shuffle();
    });
  }

  void _incrementCounter() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      // body: Center(
      //   child: ReorderableListView(
      //     scrollDirection: Axis.horizontal,
      //     onReorder: (int oldIndex, int newIndex) {
      //       if (newIndex > oldIndex) newIndex--;
      //       print("move $oldIndex to $newIndex");
      //       final box = boxes.removeAt(oldIndex);
      //       boxes.insert(newIndex, box);
      //     },
      //     children: boxes,
      //   ),
      // ),
      body: Column(
        children: [
          const SizedBox(height: 32),
          const Text(
            "welcome",
            style: TextStyle(fontSize: 32),
          ),
          const SizedBox(height: 32),
          Expanded(
            child: Listener(
              onPointerMove: (event) {
                final y = event.position.dy - _offset;
                if (y > (_slot + 1) * Box.height) {
                  if (_slot == _colors.length - 1) return;
                  setState(() {
                    final c = _colors[_slot];
                    _colors[_slot] = _colors[_slot + 1];
                    _colors[_slot + 1] = c;
                    _slot++;
                  });
                } else if (y < _slot * Box.height) {
                  if (_slot == 0) return;
                  setState(() {
                    final c = _colors[_slot];
                    _colors[_slot] = _colors[_slot - 1];
                    _colors[_slot - 1] = c;
                    _slot--;
                  });
                }
              },
              child: Stack(
                key: _globalKey,
                children: List.generate(_colors.length, (i) {
                  return Box(
                      color: _colors[i],
                      x: 50,
                      y: i * Box.height,
                      OnDrage: (Color color) {
                        print("OnDrage ${color}");
                        final index = _colors.indexOf(color);
                        final renderBox = _globalKey.currentContext
                            ?.findRenderObject() as RenderBox;
                        // _offset = renderBox.size.height; //appbar高度
                        _offset = renderBox
                            .localToGlobal(Offset.zero)
                            .dy; //全屏到关心key的位置
                        _slot = index;
                        print(
                            "OnDrage ${color} ${index}, stack height = $_offset");
                      },
                      key: ValueKey(_colors[i]));
                }),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _shuffle,
        child: Icon(Icons.refresh),
      ),
    );
  }
}

class Box extends StatelessWidget {
  final Color? color;
  final double x, y;
  final Function(Color) OnDrage;

  static const double width = 250;
  static const double height = 50;
  static const double margin = 2.0;

  const Box({
    required this.color,
    required this.x,
    required this.y,
    required this.OnDrage,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final container = Container(
      margin: EdgeInsets.all(8.0),
      width: width - margin * 2,
      height: height - margin * 2,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8.0),
      ),
    );

    return AnimatedPositioned(
      top: y,
      left: x,
      duration: Duration(milliseconds: 100),
      child: Draggable(
        onDragStarted: () => OnDrage(color!),
        child: container,
        feedback: container,
        childWhenDragging: Visibility(visible: false, child: container),
      ),
    );
  }
}
